package com.tangtang.basic.threads;

public class SynchronizedSafeDemo {
    private volatile  static  int data = 0;

    public static void main(String[] args)  throws  Exception{

        SynchronizedSafeDemo safeDemo = new SynchronizedSafeDemo();

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 20; i++) {
//                    synchronized (SynchronizedSafeDemo.class) {
//                        try {
//                            Thread.sleep(10);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        data++;
//                        System.out.println(data);
//                    }

//                    add();

//                    safeDemo.add1();

                    synchronized (safeDemo){
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        data++;
                        System.out.println(data);
                    }

                }
            }
        };
        thread1.start();
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                //1 对象Class加锁
//                synchronized (SynchronizedSafeDemo.class) {
//                    for (int i = 0; i < 20; i++) {
//                        try {
//                            Thread.sleep(10);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                        data++;
//                        System.out.println(data);
//                    }
//                }

                //2.静态方法加锁
//                add();


                //3.对象实例加锁
//                safeDemo.add1();

                synchronized (safeDemo){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    data++;
                    System.out.println(data);
                }

            }
        };
        thread2.start();

        thread1.join();
        thread2.join();
    }


    public static synchronized void add(){
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        data++;
        System.out.println(data);
    }

    public  synchronized void add1(){
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        data++;
        System.out.println(data);
    }


}
